<?php
declare (strict_types=1);
// +----------------------------------------------------------------------
// | 附件管理
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\common\model\Storage;
use think\facade\Config;
use think\facade\Filesystem;
use think\facade\View;

class StorageController extends AdminBaseController
{
    /**
     * @OA\Get(path="/attachment",tags={"附件"},summary="列表",
     *   @OA\Parameter(name="page", in="query", description="页码", @OA\Schema(type="int", default="1")),
     *   @OA\Parameter(name="limit", in="query", description="行数", @OA\Schema(type="int", default="10")),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['id'])) {
                $where[] = ['id', '=', $param['id']];
            }
            if (!empty($param['user_id'])) {
                $where[] = ['user_id', '=', $param['user_id']];
            }
            if (!empty($param['file_name'])) {
                $where[] = ['file_name', 'like', '%' . $param['file_name'] . '%'];
            }
            if (!empty($param['file_type'])) {
                $where[] = ['file_type', '=', $param['file_type']];
            }
            if (!empty($param['file_path'])) {
                $where[] = ['file_path', '=', $param['file_path']];
            }
            $list = Storage::where($where)->order('id desc')->paginate(10);
            return $this->result($list->items(), '', ['count' => $list->total()]);
        }
        return View::fetch('app/storage/list');
    }

    /**
     * @OA\Post(path="/attachment",tags={"附件"},summary="添加",
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="路径", property="path", type="string", default=""),
     *           @OA\Property(description="文件", property="file", type="resource", default=""),required={"file"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function save()
    {
        $file = $this->request->file('file');
        if (!$file) {
            $this->error('file为空');
        }
        $type              = $this->request->param('file_type', 'image');
        $type              = in_array($type, ['image', 'file', 'video', 'audio']) ? $type : 'image';
        $data['user_id']   = $this->user_id;
        $data['file_name'] = $file->getOriginalName();
        $data['file_md5']  = $file->md5();
        $data['file_sha1'] = $file->sha1();
        $data['file_ext']  = $file->extension();
        $data['file_size'] = $file->getSize();
        $data['file_type'] = $type;

        // 判断文件记录
//        $config            = Config::get('filesystem');
//        $file_info = File::where(['user_id' => $data['user_id'], 'file_sha1' => $data['file_sha1']])->find();
//        if ($file_info) {
//            $file_info['file_path'] = $config['disks'][$config['default']]['url'] . $file_info['file_path'];
//            return $this->success('文件上传成功', $file_info);
//        }

        // 本地存储
        $save_name = Filesystem::disk('public')->putFile($type, $file);
        if (!$save_name) {
            $this->error('文件上传失败');
        }
        $data['file_path'] = str_replace("\\", "/", $save_name);

        // 云存储
        //$data = Attachment::putFile($data['file_path']);
        //if ($data['code']) {
        //    $this->error($data['code']);
        //}
        $data['file_path'] = $this->request->domain() . '/storage/' . $data['file_path'];

        $result = Storage::create($data);
        $result->src = $result->file_path;
        $this->success('文件上传成功', $result);
    }

    /**
     * 显示指定的资源
     *
     * @param string $file_path
     * @return array
     */
    public function read($file_path)
    {
        return Storage::where('user_id', $this->user_id)->where('file_path', $file_path)->find();
    }

    public function edit($id)
    {
        $storage = Storage::find($id);
        View::assign('storage', $storage);
        return View::fetch('app/storage/player');
    }

    /**
     * @OA\Delete(path="/attachment",tags={"附件"},summary="删除",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="路径", property="file_path", type="string", default=""),required={"file_path"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function delete($id)
    {
        $file      = Storage::find($id);
        if (!$file) {
            return $this->success('删除成功');
        }

        // 云存储
        Storage::deleteFile($file->file_path);

        // 删除文件
        $config    = Config::get('filesystem');
        $file_path = str_replace($config['disks'][$config['default']]['url'], '', $file->file_path);
        @unlink($config['disks']['public']['root'] . '/' . $file_path);

        $result = $file->delete();
        if ($result) {
            return $this->success('删除成功');
        }
        return $this->error('删除失败');
    }

    /**
     * @OA\Get(path="/attachment/cos_sts",tags={"附件"},summary="cos sts",
     *   @OA\Parameter(name="page", in="query", description="页码", @OA\Schema(type="int", default="1")),
     *   @OA\Parameter(name="limit", in="query", description="行数", @OA\Schema(type="int", default="10")),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function cos_sts()
    {
        return json(Storage::sts());
    }
}